<?php

namespace System\Core;

if (!defined('BASEPATH')) die('Access Denied.');

/**
 * µMVC Framework (c) 2011.
 * 
 * PHP5 MVC Framework software for PHP 5.2.17 or later
 * 
 * @package         µMVC
 * @filename        system/core/loader.class.php
 * @copyright       Lanz (c) 2011.
 * 
 */

class LoaderException extends CommonException {}

/**
 * Loader class
 * Loads models, helpers and libraries.
 * 
 * @package         µMVC
 * @subpackage      Core
 * @category        System
 */
class Loader extends BaseSingleton
{
    private $_registry;
    
    function __construct()
    {
        $this->_registry = Registry::instance();
        Log::instance()->write(Log::DEBUG, 'Loader Class intitialized');
    }
    
    public function model($modelName)
    {
        if (!isset($this->_registry->{$modelName}))
        {
            if (is_readable(BASEPATH.'models'.DS.$modelName.'.class.php'))
            {
                $model = '\\System\\Models\\'.$modelName;
                $this->_registry->{$modelName} = new $model();
            }
            else
            {
                throw new LoaderException($modelName.' model does not exist.');
            }
        }   
    }
    
    public function helper($helperName)
    {
        $helperPath = BASEPATH.'helpers'.DS.$helperName.'.helper.php';
        if (is_readable($helperPath))
        {
            include $helperPath;
        }
        else
        {
            throw new LoaderException($helperName.' helper does not exist.');
        }
    }
    
    public function library($libraryName)
    {
        $libraryPath = BASEPATH.'libraries'.DS.$libraryName.'.class.php';
        if (is_readable($libraryPath))
        {
            $library = '\\System\\Libraries\\'.$libraryName;
            $this->_registry->{$libraryName} = new $library();
        }
        else
        {
            throw new LoaderException($libraryName.' library does not exist.');
        }
    }
}
?>
